package com.yls.autoapply.service;

import com.yls.autoapply.model.NameSpace;
import com.yls.autoapply.model.SshConnection;
import com.yls.autoapply.model.ServiceParam;
import com.yls.autoapply.model.ServiceResult;
import com.yls.autoapply.model.SshResponse;
import com.yls.autoapply.server.MasterServer;
import com.yls.autoapply.server.NodeServer;
import com.yls.autoapply.util.CmdUtil;
import com.yls.autoapply.util.ServerUtil;
import com.yls.autoapply.util.ServiceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoApplyService {

    public List<ServiceResult> autoApply(List<ServiceParam> params) {

        List<ServiceResult> results = new ArrayList<>();

        for (ServiceParam param : params) {
            ServiceResult result = new ServiceResult();
            result.setService(param.getService());
            result.setVersion(param.getVersion());
            List<NameSpace> nameSpaces = ServiceUtil.get(param.getService())
                    .stream().filter(x -> param.getNamespaces().contains(x.getNamespace())).collect(Collectors.toList());
            result.setNamespaces(nameSpaces.stream().map(x -> x.getNamespace()).collect(Collectors.toList()));
            for (NameSpace namespace : nameSpaces) {
                NodeServer nodeServer = new NodeServer();
                MasterServer masterServer = new MasterServer();
                try {
                    nodeServer.auth(ServerUtil.get("node"));
                    String dest = namespace.getTagPerfix() + ":" + tag(param.getVersion());
                    nodeServer.dockerTag(namespace.getTag(), dest);
                    nodeServer.dockerPush(dest);
                    masterServer.auth(ServerUtil.get("master"));
                    masterServer.sed(namespace.getFile(), "image: .*", "image: " + dest);
                    masterServer.apply(namespace.getFile());
                    String res = StringUtils.isEmpty(result.getResult()) ? "" : result.getResult() + ",";
                    result.setResult(res + "success");
                    String msg = StringUtils.isEmpty(result.getMsg()) ? "" : result.getMsg() + ",";
                    result.setMsg(msg + "success");
                } catch (Exception e) {
                    log.error("" + e);
                    String res = StringUtils.isEmpty(result.getResult()) ? "" : result.getResult() + ",";
                    result.setResult(res + "fail");
                    String msg = StringUtils.isEmpty(result.getMsg()) ? "" : result.getMsg() + ",";
                    result.setMsg(msg + e.getMessage());
                } finally {
                    nodeServer.close();
                    masterServer.close();
                }
            }
            results.add(result);
        }

        return results;

    }

    private String tag(String version) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return "v5.5." + version + "." + LocalDate.now().format(formatter);
    }

    public List<String> getImage(String service) {
        SshConnection node = ServerUtil.get("node");
        NodeServer nodeServer = new NodeServer();
        try {
            nodeServer.auth(node);
            SshResponse response = nodeServer.dockerImage(service);
            String stdOutput = response.getStdOutput();
            return Arrays.asList(stdOutput.split("\n"));
        } catch (Exception e) {
            log.error("" + e);
            return Arrays.asList(e.getMessage());
        } finally {
            nodeServer.close();
        }
    }

    public List<String> getVersion(String namespace) {
        SshConnection master = ServerUtil.get("master");
        MasterServer masterServer = new MasterServer();
        try {
            masterServer.auth(master);
            SshResponse response = masterServer.version(namespace);
            String stdOutput = response.getStdOutput();
            return Arrays.asList(stdOutput.split("\n"));
        } catch (Exception e) {
            log.error("" + e);
            return Arrays.asList(e.getMessage());
        } finally {
            masterServer.close();
        }
    }

    public String upload(String remoteDir, MultipartFile file) {
        remoteDir = "/apps/dockerBuild/files/igaweb/";
        NodeServer nodeServer = new NodeServer();
        InputStream in = null;
        try {
            in = file.getInputStream();
            nodeServer.auth(ServerUtil.get("node"));
            nodeServer.rmdir(remoteDir + "iga");
            nodeServer.upload(remoteDir, file.getOriginalFilename(), in);
            nodeServer.run(String.format(CmdUtil.unzip, remoteDir +"iga", remoteDir + file.getOriginalFilename()));
            nodeServer.run(String.format(CmdUtil.build, remoteDir));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("" + e);
            return e.getMessage();
        } finally {
            nodeServer.close();
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("" + e);
            }
        }
        return "success";
    }

    public static void main(String[] args) {
        SshConnection node = ServerUtil.get("node");
        NodeServer nodeServer = new NodeServer();
        try {
            nodeServer.auth(node);
            SshResponse response = nodeServer.dockerImage("admin");
            log.info(response.toString());
        } catch (Exception e) {

        }
    }
}
